package prueba;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

public class RecordStoreAgendaBytes extends MIDlet implements CommandListener {

	private RecordStore rs = null;
	static final String REC_STORE = "dbprueba";
	private Display pantalla;
	private Form form,crear;
	private Command comandocrear,confirmar;
	TextField nombre,direccion,telefono;
	ChoiceGroup eleccion;
	
	
	
    private static StringBuffer recBuf;
    
	public RecordStoreAgendaBytes() throws RecordStoreException {
		// TODO Auto-generated constructor stub
		pantalla = Display.getDisplay(this);
		rs = RecordStore.openRecordStore(REC_STORE, true );
		eleccion = new ChoiceGroup("Accion",ChoiceGroup.EXCLUSIVE);
		eleccion.insert(0,"Nuevo" , null);
		eleccion.insert(1, "Modificar", null);
		eleccion.insert(2, "Eliminar", null);
		
		readRecords();
		
		form=new Form("RecordStore Prueba");
		crear=new Form("Crear registro");
		nombre= new TextField("Nombre:","",10,TextField.ANY);
		direccion= new TextField("Direccion:","",40,TextField.ANY);
		telefono= new TextField("Telefono:","",10,TextField.PHONENUMBER);
		
		crear.append(nombre);
		crear.append(direccion);
		crear.append(telefono);
		comandocrear=new Command("Crear Campo",Command.OK, 0);
		confirmar=new Command("Confirmar",Command.OK, 0);
		form.addCommand(comandocrear);
		form.append(eleccion);
		crear.addCommand(confirmar);
		pantalla.setCurrent(form);
		form.setCommandListener(this);
		crear.setCommandListener(this);
		
		
		 
		 
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		// TODO Auto-generated method stub
		try {
			rs.closeRecordStore();
		} catch (RecordStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void pauseApp() {
		// TODO Auto-generated method stub

	}

	protected void startApp() throws MIDletStateChangeException {
		// TODO Auto-generated method stub

	}

	public void commandAction(Command arg0, Displayable arg1) {
		// TODO Auto-generated method stub
		if(arg0.equals(comandocrear)){
			pantalla.setCurrent(crear);
		}else if(arg0.equals(confirmar)){
			writeRecord(nombre.getString()+ " - " +direccion.getString() + " - " +telefono.getString() +" \n");
			nombre.delete(0, nombre.size());
			direccion.delete(0, direccion.size());
			telefono.delete(0, telefono.size());
			pantalla.setCurrent(form);
			
			readRecords();
			
		}
	}
	
	public void writeRecord(String str)
	  {
	    byte[] rec = str.getBytes();

	    try
	    {
	      rs.addRecord(rec, 0, rec.length);
	    }
	    catch (Exception e)
	    {
	    
	    }
	  }

	
	 public void readRecords()
	  {
	    try
	    {
	      // Intentionally make this too small to test code below
	      byte[] recData = new byte[5]; 
	      int len;

	      for (int i = 1; i <= rs.getNumRecords(); i++)      
	      {
	        if (rs.getRecordSize(i) > recData.length)
	          recData = new byte[rs.getRecordSize(i)];
	       
	        len = rs.getRecord(i, recData, 0);
	        form.append("Record #" + i + ": " + new String(recData, 0, len) + "\n");                            
	      }
	    }
	    catch (Exception e)
	    {
	      
	    }
	  }
	 static boolean createRecordStore(String name,
		             String[] seedData) {
		RecordStore recordStore;
		boolean ret = false;
		// Delete any previous record store with same name.
		// Silently ignore failure.
		try {
		RecordStore.deleteRecordStore(name);
		} catch (Exception rse) {}
		
		// Create new RMS store. If we fail, return false.
		try {
		recordStore = RecordStore.openRecordStore(name, true);
		} catch (RecordStoreException rse) {
		return ret;
		}
		
		ret = true; // assume success
		
		// Now, populate the record store with the seed data
		for (int i = 0; i < seedData.length; i += 3) {
		byte[] record = createRecord(seedData[i],
		                              seedData[i+1],
		                              seedData[i+2]);
		
		try {
		recordStore.addRecord(record, 0, record.length);
		} catch (RecordStoreException rse) {
		ret = false;
		break;
		}
		}
		
		// Get here when adds are complete, or an error occured.
		// In any case, close the record store. We shouldn't
		// have a failure, so silently ignore any exceptions.
		try {
		recordStore.closeRecordStore();
		} catch (RecordStoreException rsne) {}
		
		return ret;
		}

	
	 public static byte[] createRecord(String first,
             String last,
             String num) {
			
//			recBuf.insert(FIRST_NAME_INDEX, first);
//			recBuf.insert(LAST_NAME_INDEX, last);
//			recBuf.insert(PHONE_INDEX, num);
//			recBuf.setLength(MAX_REC_LEN);
			return recBuf.toString().getBytes();
			
	}
}
